package com.lefevre.cms.web.action;

import com.lefevre.cms.bean.QueryResult;
import com.lefevre.cms.bean.RequestResult;
import com.lefevre.cms.bean.ResultCode;
import com.lefevre.cms.bean.staff.StaffLoginLog;
import com.lefevre.cms.bean.staff.SysUsers;
import com.lefevre.cms.service.feedback.FeedbackService;
import com.lefevre.cms.service.question.AnswerService;
import com.lefevre.cms.service.question.QuestionService;
import com.lefevre.cms.service.staff.StaffService;
import com.lefevre.cms.service.topic.CommentService;
import com.lefevre.cms.service.topic.TopicService;
import com.lefevre.cms.utils.FileUtil;
import com.lefevre.cms.utils.IpAddress;
import com.lefevre.cms.utils.JsonUtils;
import com.lefevre.cms.utils.WebUtil;
import com.lefevre.cms.web.action.fileSystem.FileManage;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 后台框架页面
 *
 * @author Lefevre
 */
@Controller
public class AdminController {

    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Resource
    StaffService staffService;
    @Resource
    TopicService topicService;
    @Resource
    CommentService commentService;
    @Resource
    QuestionService questionService;
    @Resource
    AnswerService answerService;
    @Resource
    FeedbackService feedbackService;
    @Resource
    FileManage fileManage;

    /**
     * 后台管理框架页
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("control/manage/index")
    public String framework() {
        Map<String, Object> returnValue = new HashMap<>();
        SysUsers sysUserView = new SysUsers();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            Object o = authentication.getPrincipal();
            if (o instanceof SysUsers) {
                SysUsers sysUsers = (SysUsers) o;
                sysUserView.setUserId(sysUsers.getUserId());
                sysUserView.setUserAccount(sysUsers.getUserAccount());
                sysUserView.setFullName(sysUsers.getFullName());
                sysUserView.setUserDuty(sysUsers.getUserDuty());
                sysUserView.setIssys(sysUsers.isIssys());
            }
        }
        returnValue.put("sysUsers", sysUserView);
        //文件存储系统 0.本地系统 10.SeaweedFS 20.MinIO 30.阿里云OSS
        returnValue.put("fileStorageSystem", fileManage.getFileSystem());
        return JsonUtils.toJSONString(new RequestResult(ResultCode.SUCCESS, returnValue));
    }

    /**
     * 后台首页
     */
    @ResponseBody
    @RequestMapping("control/manage/home")
    public String home() throws Exception {
        Map<String, Object> returnValue = new HashMap<>(16);

        SysUsers sysUsers = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            Object o = authentication.getPrincipal();
            if (o instanceof SysUsers) {
                sysUsers = (SysUsers) o;
            }
        }

        assert sysUsers != null;
        QueryResult<StaffLoginLog> qr = staffService.findStaffLoginLogPage(sysUsers.getUserId(), 0, 5);
        List<StaffLoginLog> staffLoginLogList = qr.getResultlist();
        if (staffLoginLogList != null && staffLoginLogList.size() > 0) {
            for (StaffLoginLog staffLoginLog : staffLoginLogList) {
                if (staffLoginLog.getIp() != null && !"".equals(staffLoginLog.getIp().trim())) {
                    staffLoginLog.setIpAddress(IpAddress.queryAddress(staffLoginLog.getIp()));
                }
            }
        }
        returnValue.put("staffLoginLogList", staffLoginLogList);

        Long auditTopicCount = topicService.auditTopicCount();
        returnValue.put("auditTopicCount", auditTopicCount);

        Long auditCommentCount = commentService.auditCommentCount();
        returnValue.put("auditCommentCount", auditCommentCount);

        Long auditCommentReplyCount = commentService.auditReplyCount();
        returnValue.put("auditCommentReplyCount", auditCommentReplyCount);

        Long auditQuestionCount = questionService.auditQuestionCount();
        returnValue.put("auditQuestionCount", auditQuestionCount);
        Long auditAnswerCount = answerService.auditAnswerCount();
        returnValue.put("auditAnswerCount", auditAnswerCount);

        Long auditAnswerReplyCount = answerService.auditReplyCount();
        returnValue.put("auditAnswerReplyCount", auditAnswerReplyCount);

        Long feedbackCount = feedbackService.feedbackCount();
        returnValue.put("feedbackCount", feedbackCount);

        return JsonUtils.toJSONString(new RequestResult(ResultCode.SUCCESS, returnValue));
    }

    /**
     * 后台管理框架页
     *
     * @return
     */
    @RequestMapping("admin/control/**")
    public String index() throws Exception {
        //List<String> templatePathList = WebUtil.templatePathList();
        //model.addAttribute("templatePathList", templatePathList);
        return "/manage/index";
    }


    /**
     * vue组件加载
     * 本方法权限验证由cms.web.action.staff.MyBearerTokenExtractor.java和cms.web.action.staff.ResourceServerConfig.java和cms.web.action.staff.WebSecurityConfig.java进行拦截
     *
     * @return
     */
    @RequestMapping("admin/component/{path}/{name}")
    public ResponseEntity<byte[]> component(@PathVariable String path, @PathVariable String name, HttpServletRequest request) {
        ClassPathResource classPathResource = new ClassPathResource("WEB-INF/admin/manage/" + FileUtil.toRelativePath(path) + "/" + FileUtil.toRelativePath(FileUtil.getBaseName(name) + ".vue"));
        if (classPathResource.exists()) {
            try (InputStream inputStream = classPathResource.getInputStream()) {
                byte[] bytes = IOUtils.toByteArray(inputStream);
                return WebUtil.downloadResponse(bytes, FileUtil.getName(path), request);
            } catch (IOException e) {
                logger.error("vue组件加载错误", e);
            }
        }
        return null;
    }
}
